<template>
  <el-dialog
    title="确认收货"
    top="5vh"
    :visible.sync="dialogVisible"
    width="80%"
    :close-on-click-modal="false"
    append-to-body
  >
    <div class="confirm-receipt">
      <!-- 采购单信息 -->
      <div class="menu-info">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="菜单标题">{{ currentMenu?.title }}</el-descriptions-item>
          <el-descriptions-item label="菜单日期">{{ formatDate(currentMenu?.menu_date) }}</el-descriptions-item>
          <el-descriptions-item label="供应商">{{ currentMenu?.supplier?.name }}</el-descriptions-item>
          <el-descriptions-item label="采购员">{{ currentMenu?.purchaser?.name }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag type="primary">采购中</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 菜品明细表格 -->
      <div class="dish-details">
        <h4>菜品明细</h4>
        <el-table
          :data="menuItems"
          v-loading="loading"
          border
          stripe
        >
          <el-table-column prop="dish.category" label="菜品分类" width="80">
            <template slot-scope="scope">
              {{ scope.row.dish?.category || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="dish.name" label="菜品名称" width="150">
            <template slot-scope="scope">
              {{ scope.row.dish?.name || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="dish.unit" label="单位" width="80">
            <template slot-scope="scope">
              {{ scope.row.dish?.unit || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="base_price" label="官方参考价格" width="100">
            <template slot-scope="scope">
              ¥{{ scope.row.base_price }}
            </template>
          </el-table-column>
          <el-table-column prop="supplier_quoted_price" label="供应商报价" width="120">
            <template slot-scope="scope">
              ¥{{ scope.row.supplier_quoted_price }}
            </template>
          </el-table-column>
          <el-table-column prop="planned_quantity" label="计划采购数量" width="100">
            <template slot-scope="scope">
              {{ scope.row.planned_quantity }}
            </template>
          </el-table-column>
          <el-table-column prop="actual_price" label="供应商-实际采购价" width="150">
            <template slot-scope="scope">
              ¥{{ scope.row.actual_price || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="actual_quantity" label="供应商-实际采购数量" width="150">
            <template slot-scope="scope">
              {{ scope.row.actual_quantity || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="actual_quantity2" label="实际收货数量" width="180">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.actual_quantity2"
                :min="0"
                :precision="2"
                :step="0.1"
                size="mini"
                style="width: 120px"
                placeholder="请输入"
              />
            </template>
          </el-table-column>
          <el-table-column prop="quality_rating" label="品质评价" width="150">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.quality_rating"
                placeholder="请选择"
                size="mini"
                style="width: 120px"
              >
                <el-option v-for="item in (dishRatingMap[`${scope.row.dish.category}-${scope.row.dish.name}`] || ['好', '中', '差'])" :key="item" :label="item" :value="item" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.remark"
                type="textarea"
                size="mini"
                :rows="2"
                placeholder="请输入备注"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 收货统计 -->
      <div class="receipt-summary" v-if="menuItems.length > 0">
        <el-alert
          title="收货统计"
          type="info"
          :closable="false"
          show-icon
        >
          <div slot="description">
            <p>总菜品数：{{ menuItems.length }} 个</p>
            <p>已填写收货数量：{{ filledQuantityCount }} 个</p>
            <p>已填写品质评价：{{ filledQualityCount }} 个</p>
          </div>
        </el-alert>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmReceipt" :loading="saving" :disabled="!canConfirm">
        确认收货
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { http } from '@/api'

export default {
  name: 'ConfirmReceipt',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    currentMenu: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      saving: false,
      menuItems: [],
      dishRatingMap: {}
    }
  },
  computed: {
    filledQuantityCount() {
      return this.menuItems.filter(item =>
        item.actual_quantity2 !== null &&
        item.actual_quantity2 !== undefined &&
        item.actual_quantity2 > 0
      ).length;
    },
    filledQualityCount() {
      return this.menuItems.filter(item =>
        item.quality_rating &&
        item.quality_rating.trim() !== ''
      ).length;
    },
    canConfirm() {
      return this.menuItems.length > 0 &&
             this.filledQuantityCount === this.menuItems.length &&
             this.filledQualityCount === this.menuItems.length;
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val && this.currentMenu) {
        this.loadMenuItems()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
      if (!val) {
        this.resetData()
      }
    }
  },
  created() {
    http.dishRating.list().then(res => {
      let dishRatingMap = {}
      // 将不同分类使用map形式
      res.data.forEach(item => {
        let key = `${item.category}-${item.dish_name}`
        if (!dishRatingMap[key]) {
          dishRatingMap[key] = item.rating_value.split(',')
        }
      })
      this.dishRatingMap = dishRatingMap
      console.log('dishRatingMap',dishRatingMap);

    })
  },
  methods: {
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleDateString('zh-CN');
    },

    async loadMenuItems() {
      this.loading = true
      try {
        const res = await http.dailyMenuItem.getMenuItems(this.currentMenu.id);

        this.menuItems = res.data || [];

        // 初始化未填写的字段
        this.menuItems.forEach(item => {
          if (item.actual_quantity2 === null || item.actual_quantity2 === undefined) {
            item.actual_quantity2 = null;
          }
          if (!item.quality_rating) {
            item.quality_rating = '';
          }
          if (!item.remark) {
            item.remark = '';
          }
        });

      } catch (error) {
        console.error('加载菜品明细失败:', error);
        this.$message.error('加载菜品明细失败');
      } finally {
        this.loading = false;
      }
    },

    async confirmReceipt() {
      if (!this.canConfirm) {
        this.$message.warning('请完善所有菜品的收货数量和品质评价');
        return;
      }

      this.saving = true;
      try {
        // 批量更新菜品明细
        const updateData = this.menuItems.map(item => ({
          daily_menu_id: this.currentMenu.id,
          id: item.id,
          actual_quantity2: item.actual_quantity2,
          quality_rating: item.quality_rating,
          remark: item.remark,
          status: 3 // 已收货状态
        }));

        await http.dailyMenuItem.batchConfirmReceipt(updateData);
        this.$message.success('确认收货成功');
        this.dialogVisible = false;
        this.$emit('success');

      } catch (error) {
        console.error('确认收货失败:', error);
        this.$message.error('确认收货失败: ' + (error.message || '未知错误'));
      } finally {
        this.saving = false;
      }
    },

    resetData() {
      this.menuItems = [];
    }
  }
}
</script>

<style scoped lang="scss">
.confirm-receipt {
  .menu-info {
    margin-bottom: 20px;
  }

  .dish-details {
    margin-bottom: 20px;

    h4 {
      margin: 0 0 15px 0;
      color: #303133;
      font-size: 16px;
    }
  }

  .receipt-summary {
    margin-top: 20px;
  }
}

.dialog-footer {
  text-align: right;
}
</style>
